package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.UserLocationVo;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class UserLocationApiImpl implements UserLocationApi {


    @Autowired
    private MongoTemplate mongoTemplate;

    //保存或者更新当前地址
    @Override
    public void saveLocation(Long userId,Double longitude, Double latitude, String addrStr) {
        //查询当前登陆者是否有地理位置的记录，如果没有插入，如果有更新
        Query query = new Query(Criteria.where("userId").is(userId));
        if(!mongoTemplate.exists(query, UserLocation.class)){
            //如果没有记录，是插入
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userLocation.setAddress(addrStr);
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis());
            mongoTemplate.save(userLocation);
        }else{
            //更新
            Update update = new Update();
            update.set("location",new GeoJsonPoint(longitude,latitude));
            update.set("address",addrStr);
            update.set("updated",System.currentTimeMillis());
            update.set("lastUpdated",System.currentTimeMillis());
            mongoTemplate.updateFirst(query,update, UserLocation.class);
        }


    }

    //搜索附近的人
    @Override
    public List<UserLocation> searchNear(long userId, Long distance) {
        //1. 找出圆心
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint location = userLocation.getLocation();

        //2. 找出半径
        Distance distance1 = new Distance(distance/1000, Metrics.KILOMETERS);

        //3. 画一个圆
        Circle circle = new Circle(location,distance1);


        //4. 根据圆范围去搜索
        Query nearQuery = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(nearQuery, UserLocation.class);

        return userLocationList;
    }
}
